import 'dart:convert';

import 'package:app/core/net/apis.dart';
import 'package:app/core/net/entity/base_list_entity.dart';
import 'package:app/core/net/request.dart';
import 'package:app/core/utils/helpers/sp.dart';
import 'package:app/data/services/store_service.dart';
import 'package:app/page/login/entity/entity_login.dart';
import 'package:get/get.dart';

import '../../../configs.dart';
import 'entity/friend_entity.dart';
import 'state.dart';

class FriendLogic extends GetxController {
  final state = FriendState();
  StorageController controller = Get.find<StorageController>();
  StoreService _storeService = Get.find<StoreService>();

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    /// TODO 需要优化
    queryFriend();
    _storeService.init();
  }

  refreshFriend() {
    if (Configs.userID == -1) {
      Configs.userID =
          LoginEntity.fromJson(json.decode(controller.userInfo)).userId;
    }
    var params = {"user_id": '${Configs.userID}'};

    post(Apis.FRIENDS_SHOW_URL, params)
        .listen((event) {}, onDone: () {})
        .onData((data) {
      var bean = BaseListEntity<FriendEntity>.fromJson(data);
      if (bean == null) {
      } else {
        if (bean.code == 200) {
          state.friends = bean.data.list;
          // bean.data.list.map((e) =>
          //     _storeService.database.insertFriend(
          //         e.user_name, e.phone, e.remark, e.picurl));

          // _storeService.database.insertFriend(name, phone)
        } else {}
      }
    });
  }

  queryFriend() {
    if (Configs.userID == -1) {
      Configs.userID =
          LoginEntity.fromJson(json.decode(controller.userInfo)).userId;
    }
    var params = {"user_id": '${Configs.userID}'};

    post(Apis.FRIENDS_SHOW_URL, params)
        .listen((event) {}, onDone: () {})
        .onData((data) {
      var bean = BaseListEntity<FriendEntity>.fromJson(data);
      if (bean == null) {
      } else {
        if (bean.code == 200) {
          state.friends = bean.data.list;
          // LogPrint.getInstance().printInfo(bean.data.list.toString());

          state.friends.forEach((FriendEntity e) {
            print("WTF ${e.friend_name} ");
            _storeService.database
                .insertFriend(e.friend_name, e.phone, e.remark, e.picurl);
          });
          //
          // _storeService.database.allFriends().then((value) {
          // });

          // _storeService.database.insertFriend(name, phone)
        } else {}
      }
    });

    // Stream<>
    // _storeService.database.watchAllFriends()?.map((event) => null)
  }
}
